# -*- coding:utf-8 -*-
# Author:Ami
# @Time    : 2018/12/9 9:27

import socket

client = socket.socket()

client.connect(('localhost', 9999))

while True:
    cmd = input(">>:").strip()
    if len(cmd) == 0:
        continue
    if cmd.startswith("get"):
        client.send(cmd.encode())
        server_response = client.recv(1024)
        print("文件大小:", server_response)
        client.send(b"ready to recv file")
        file_total_size = int(server_response.decode())
        received_size = 0
        filename = cmd.split()[1]
        f = open(filename, "wb")
        while received_size < file_total_size:
            data = client.recv(1024)
            received_size+=len(data)
            f.write(data)
            # print(file_total_size,received_size)
        else:
            print("下载完毕",received_size,file_total_size)
            f.close()
    # client.send(cmd.encode("utf-8"))  # 转bytes类型
    # cmd_res_size = client.recv(1024)  # 接收结果的长度
    # print("文件大小",cmd_res_size)
    # client.send("准备好接受了".encode("utf-8"))
    # received_size = 0
    # received_data = b""
    # while received_size != int(cmd_res_size.decode()):
    #     data = cmd_res = client.recv(1024)
    #     received_size += len(data)  # 每次收到的有可能小于1024
    #     # print(data)
    #     # print(data.decode())
    #     received_data += data
    #     print(received_size)
    # else:
    #     print('cmd res receive done...', received_size)
    #     print(received_data.decode())

    # print(cmd_res)
    # print(cmd_res.decode())

client.cloce()
